<template>
  <div class="flex flex-col">
    <div
      class="flex justify-between items-center border p-3 mb-15px rounded-md"
      style="box-shadow: 4px 4px 6px rgba(0, 0, 0, 0.2)"
    >
      <div class="space-x-10">
        <span>
          当前时间：
          <span class="font-bold text-2xl">{{ countUpTime || '--' }}</span>
        </span>
        <span
          >标段时间：
          <span v-if="resultData?.startTime && resultData?.endTime">
            {{ resultData?.startTime || '--' }}-{{ resultData?.endTime || '--' }}
          </span>
          <span v-else>--/--</span>
        </span>
        <span>保证金：￥{{ resultData?.securityDeposit || 0 }}</span>
        <span
          >交易方式：{{
            getDictLabel(DICT_TYPE.BID_TRADING_WAY, resultData?.tradingWay?.toString())
          }}</span
        >
      </div>
      <div>
        <el-button type="primary" @click="subPage(1)">详情</el-button>
        <el-button @click="goBack">返回</el-button>
      </div>
    </div>
    <ContentWrap>
      <el-container class="flex justify-between">
        <div>
          <div class="space-x-8 font-bold">
            <span
              class="status"
              :class="{
                'bg-sky-500': resultData?.status === 10,
                'bg-lime-500': resultData?.status === 20,
                'bg-stone-400': resultData?.status === 30,
                'bg-red-500': resultData?.status === 40
              }"
              >{{
                getDictLabel(DICT_TYPE.BID_ACTION_SETIO_SORT, resultData?.status?.toString())
              }}</span
            >
            <span>场次：{{ resultData?.sessionCode || '--' }}</span>
            <span v-if="resultData?.coalName">{{ resultData?.coalName }}</span>
            <span v-else>--</span>
          </div>
          <div class="pt-30px flex items-center">
            <span>倒计时：</span>
            <span v-if="isShowCountDown && countDown" class="text-6xl text-red-700 ml-20px">
              {{ countDownTime }}
            </span>
            <span v-else class="text-6xl text-red-700 ml-20px">--:--</span>
          </div>
        </div>
        <div class="flex">
          <div class="space-y-6 mr-100px">
            <div>
              <span class="text-label"
                >{{ `${resultData?.tradingWay === 3 ? '挂牌' : '起拍'}价` }}：</span
              >
              <span>
                <span v-if="resultData?.startingPrice">
                  ￥{{ resultData?.startingPrice || 0 }}
                </span>
                <span v-else>￥--/--</span>
              </span>
            </div>
            <div>
              <span class="text-label">数量：</span>
              <span>
                <span v-if="isEmpty(resultData?.tradingAmount)">
                  {{ resultData?.tradingAmount || 0 }}吨
                </span>
                <span v-else>--</span>
              </span>
            </div>
            <div>
              <span class="text-label">交货周期：</span>
              <span>{{ resultData?.deliveryCycle || '--' }}</span>
            </div>
          </div>
          <div class="space-y-6 mr-100px">
            <div>
              <span class="text-label">最新报价：</span>
              <span class="text-xl text-red-700 font-bold">
                <span v-if="isShowMaxQuotePrice"> ￥{{ maxQuotePrice }} </span>
                <span v-else>--</span>
              </span>
            </div>
            <div>
              <span class="text-label">剩余量：</span>
              <span>
                <span v-if="isEmpty(resultData?.overAmount)">
                  {{ resultData?.overAmount || 0 }}吨
                </span>
                <span v-else>--</span>
              </span>
            </div>
            <div>
              <span class="text-label">交货地：</span>
              <span>{{ resultData?.deliveryPlace || '--' }}</span>
            </div>
          </div>
        </div>
      </el-container>
    </ContentWrap>
    <div class="flex-1">
      <el-table
        v-loading="loading"
        :data="list"
        border
        stripe
        :height="'100%'"
        :header-cell-style="{ background: '#F3F4F7', color: '#555' }"
      >
        <el-table-column label="序号" align="center" width="60" fixed="left">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          label="标段号"
          align="center"
          prop="markCode"
          min-width="180"
          fixed="left"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="状态" align="center" prop="status" width="150">
          <template #default="{ row }">
            <dict-tag :type="DICT_TYPE.BID_ACTION_SETIO_SORT" :value="row.status" />
          </template>
        </el-table-column>
        <el-table-column label="产品名称" align="center" prop="coalName" width="100">
        </el-table-column>
        <el-table-column
          :label="`${resultData?.tradingWay === 3 ? '挂牌' : '起拍'}价格(元/吨)`"
          align="center"
          prop="startingPrice"
          width="150"
        />
        <el-table-column label="交易量(吨)" align="center" prop="tradingAmount" width="150" />
        <el-table-column label="中标价(元/吨)" align="center" prop="bidPrice" width="150">
          <template #default="{ row }">
            <span class="text-red-700">{{ row.bidPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="中标量(吨)" align="center" prop="bidAmount" width="150" />
        <el-table-column label="中标客户" align="center" prop="customerName" width="150" />
        <el-table-column label="竞拍时间(开始)" align="center" prop="startTime" min-width="150" />
        <el-table-column label="竞拍时间(结束)" align="center" prop="endTime" min-width="150" />
      </el-table>
    </div>
  </div>
</template>
<script setup lang="ts" name="auctionDetail">
import { computed, onMounted, reactive, ref } from 'vue'
import * as Utils from '@/utils/dict'
import * as bidding from '@/api/bidding'
import { useRouter } from 'vue-router'
import { formatDate } from '@/utils/formatTime'
import { getAccessToken, getTenantId } from '@/utils/auth'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { isEmpty } from '@/utils/common'
import Socket from '@/utils/socket'

const { DICT_TYPE, getDictLabel } = reactive(Utils)
const router = useRouter()
const message = useMessage()
const loading = ref(true) // 列表的加载中
const resultData: Record<string, any> = ref(null)
const list = ref([]) // 列表的数据
const countDown = ref(0)
const isShowCountDown = ref(false)
const countDownTime = computed(() => {
  return formatDate(new Date(countDown.value), 'mm:ss')
})
const countUp = ref(new Date().getTime())
const countUpTime = computed(() => {
  return formatDate(new Date(countUp.value), 'HH:mm:ss')
})
const isBeginBidding = ref(false)
const currentTimer: Record<string, any> = ref(null)
const countdownTimer: Record<string, any> = ref(null)
const curDate = computed(() => {
  return formatDate(new Date(), 'YYYY-MM-DD')
})
const maxQuotePrice = ref(0)
const route = useRoute()
const rowId = ref()
const { wsCache } = useCache()
const emit = defineEmits(['subPage'])

const isShowMaxQuotePrice = computed(() => {
  return (
    resultData.value?.tradingWay === 1 && resultData.value?.status !== 30 && maxQuotePrice.value
  )
})

let socket = null as any
let isSocket = true

/** 查询列表 */

const getList = async () => {
  loading.value = true
  try {
    const data = await bidding.getActionDetail({ id: rowId.value })
    resultData.value = data.actionHallTopVO || {}
    if (resultData.value?.currentTime) {
      countUp.value = new Date(`${curDate.value} ${resultData.value?.currentTime}`)?.getTime()
    }
    list.value = data.sectionMessageRespVOS || []
  } finally {
    loading.value = false
  }
}

const countDownHandle = () => {
  countdownTimer.value = setInterval(() => {
    countDown.value -= 1000
    if (countDown.value <= 0) {
      console.log('结束计时')
      maxQuotePrice.value = 0
      isSocket = true
      isShowCountDown.value = false
      clearInterval(countdownTimer.value)
      socket?.close()
    }
  }, 1000)
}

const currentTimeHandle = () => {
  currentTimer.value = setInterval(() => {
    countUp.value += 1000
    if (isStartUpSocket() && isSocket && resultData.value?.tradingWay === 1) {
      console.log('开始连接websocket')
      isSocket = false
      initWebSocket()
    }
    if (getInitTime() === 60 * 1000) {
      isShowCountDown.value = true
      countDown.value = getInitTime()
      console.log('开始计时')
      countDownHandle()
    }
    if (isBeginBidding.value !== isBeginBiddingHandle()) {
      getList()
      console.log('刷新列表')
      if (isCacheCountDown()) {
        isShowCountDown.value = true
        countDown.value = getInitTime()
        console.log('开始计时')
        countDownHandle()
      }
    }
    isBeginBidding.value = isBeginBiddingHandle()
  }, 1000)
}

const isCacheCountDown = () => {
  return isBeginBiddingHandle() && getInitTime() !== 60 * 1000 && getInitTime() > 0
}

const isBeginBiddingHandle = () => {
  const curTime = countUp.value
  return list.value.some((e: Record<string, any>) => {
    const startTime = new Date(`${curDate.value} ${e.startTime}`).getTime()
    const endTime = new Date(`${curDate.value} ${e.endTime}`).getTime()
    return curTime >= startTime && curTime <= endTime
  })
}

const goBack = () => {
  router.push({ path: '/bidManageAdmin/bidding/bidOffice' })
}

const getCurrentData = () => {
  const curTime = countUp.value
  const item: Record<string, any> = list.value.filter((e: Record<string, any>) => {
    const startTime = new Date(`${curDate.value} ${e.startTime}`).getTime()
    const endTime = new Date(`${curDate.value} ${e.endTime}`).getTime()
    return curTime >= startTime && curTime < endTime
  })[0]
  return item
}

const isStartUpSocket = () => {
  const curTime = countUp.value
  const item: Record<string, any> = getCurrentData()
  if (item?.startTime) {
    const startTime = new Date(`${curDate.value} ${item.startTime}`).getTime()
    return curTime > startTime
  }
  return false
}

const getInitTime = () => {
  const curTime = countUp.value
  const item: Record<string, any> = getCurrentData()
  if (!item) {
    return 0
  }
  const endTime = new Date(`${curDate.value} ${item.endTime}`).getTime()
  const timeDiffer = (endTime - curTime) / 1000
  if (timeDiffer > resultData.value?.countdown) {
    return 0
  }
  return timeDiffer * 1000
}

const subPage = async (index: number) => {
  emit('subPage', index, rowId.value)
}

const initWebSocket = () => {
  const options = {
    url: `${
      import.meta.env.VITE_BASE_URL
    }/websocket/quotePrice/${getAccessToken()}/${getTenantId()}`,
    timer: 10 * 1000,
    reconnect: false,
    params: {
      id: resultData.value?.id,
      userId: wsCache.get(CACHE_KEY.USER)?.user?.id,
      userSource: 0,
      tenantId: getTenantId()
    },
    onmessage
  }
  socket = new Socket(options)
}

const onmessage = (data) => {
  if (data?.data) {
    const suc = JSON.parse(data?.data)
    if (suc?.code === 403) {
      message.notifyWarning(suc?.msg)
      return
    }
    if (suc?.code === 500) {
      message.notifyWarning(suc?.msg)
      return
    }
    if (suc?.code === 0) {
      maxQuotePrice.value = suc?.data?.quotePrice || 0
    }
  }
}

const visibilityChange = () => {
  if (document.visibilityState === 'visible') {
    location.reload()
  }
}

/** 初始化 **/
onMounted(async () => {
  document.addEventListener('visibilitychange', visibilityChange)
  if (route.query.id) {
    rowId.value = route.query.id
    await getList()
    currentTimeHandle()
  }
})

onBeforeUnmount(() => {
  clearInterval(currentTimer.value)
  clearInterval(countdownTimer.value)
  document.removeEventListener('visibilitychange', visibilityChange)
  socket?.close()
})
</script>
<style lang="scss" scoped>
.status {
  font-size: 14px;
  border-bottom-right-radius: 16px;
  border-top-right-radius: 16px;
  @apply px-10px py-6px text-light-50 -ml-20px;
}

.text-label {
  @apply inline-block w-100px text-right;
}
</style>
